﻿$(document).on("pagebeforeload", function (event, data) {
    // Let the framework know we're going to handle the load.
    event.preventDefault();
    // ... load the document then insert it into the DOM ...
    // at some point, either in this callback, or through
    // some other async means, call resolve, passing in
    // the following args, plus a jQuery collection object
    // containing the DOM element for the page.
    data.deferred.resolve(data.absUrl, data.options);
});

$(document).on('pageshow', function (event, ui) {
    KevinShop.Common.ShoppingCart.RefreshTotalQty();

});
$(document).bind("pagebeforeload", function (event, data) {
    KevinShop.Common.Loading.show();
});
$(document).bind("pagechange", function (event, data) {
    KevinShop.Common.Loading.hide();
});
$(document).bind("pagechangefailed", function (event, data) {
    KevinShop.Common.Loading.hide();
});

//shopping cart helper
KevinShop.Common.ShoppingCart = {
    Key: "KsShoppingCart",
    TotalQty: 0,
    TotalAmount: 0,
    GetProductList: function () {

        var list = $.cookie(this.Key);
        if (list) {
            return KevinShop.Common.EvalJSON(list);
        }
    },
    GetProductListStr: function () {

        var list = $.cookie(this.Key);
        if (list) {
            return list;
        }
    },
    ShowCartInfo: function () {
        var list = $.cookie(this.Key);

        alert(list);
    },
    UpdateToCartForQty: function (productId, qty) {
        this.UpdateToCart(productId, qty, true);
    },
    UpdateToCart: function (productId, qty, overwrite) {

        var _num = 1;
        if (qty != undefined)
            _num = Number(qty);
        var cookieSet = { expires: 30, path: '/' }; //设置cookie路径的
        //$.cookie(this.Key, null, cookieSet);//清除Cookie
        //var jsonStr ="\"[{'ProductId':'" + productId + "','Quantity':" + _num + "}]"; //构造json字符串,id是商品id   num是这个商品的数量
        var product = [{ ProductId: productId, Quantity: _num }];
        var jsonStr = KevinShop.Common.ToJSON(product);

        var value = $.cookie(this.Key);
        if (value == null || value == "") {
            $.cookie(this.Key, jsonStr, cookieSet); //如果没有这个cookie就设置他 
        }
        else {
            var jsonObj = KevinShop.Common.EvalJSON($.cookie(this.Key)); //如果有，把json字符串转换成对象
            var findProduct = false; //是否找到产品ID,找到则为TRUE,否则为FALSH
            for (var obj in jsonObj) {
                if (jsonObj[obj].ProductId == productId) {
                    jsonObj[obj].Quantity = overwrite ? qty : Number(jsonObj[obj].Quantity) + _num;
                    findProduct = true;
                    break;
                }
            }
            if (findProduct == false) { //没找到,则添加
                jsonObj[jsonObj.length] = new Object();
                jsonObj[jsonObj.length - 1].ProductId = productId;
                jsonObj[jsonObj.length - 1].Quantity = _num;
            }

            $.cookie(this.Key, KevinShop.Common.ToJSON(jsonObj), cookieSet);  //写入coockie   JSON需要json2.js支持
        }
        this.RefreshTotalQty();
    },
    DeletePrdFromCart: function (productId) {
        //remove cart info
        var carId = "#cartp_" + productId;
        $("#cartp_" + productId).remove();

        var jsonObj = KevinShop.Common.EvalJSON($.cookie(this.Key)); //get the product form cart 

        for (var obj in jsonObj) {
            if (jsonObj[obj].ProductId == productId) {
                jsonObj[obj] = undefined;
                break;
            }
        }
        var cookieSet = { expires: 30, path: '/' }; //设置cookie路径的
        $.cookie(this.Key, $.toJSON(jsonObj), cookieSet);

        //refresh cartinfo
        this.RefreshTotalQty();
    },
    RefreshTotalQty: function () {
        var list = this.GetProductList();
        var total = 0;
        var totalAcount = 0;
        for (var obj in list) {
            total += !isNaN(list[obj].Quantity) ? Number(list[obj].Quantity) : 0;
        };
        if (total > 0) {
            $("#headershoppingcart").html("<div id='num'>" + total + "</div>");
        } else {
            $("#headershoppingcart").html("");
        }

        this.TotalAmount = totalAcount;
        this.TotalQty = total;
    },
    ClearCart: function () {
        var cookieSet = { expires: 0, path: '/' }; //设置cookie路径的
        $.cookie(this.Key, null, cookieSet);
    },
    CheckQuantity: function (qty, lqty) {
        if (isNaN(qty)) {
            KevinShop.MessageBox.Alert("必须输入有效的数量。");
            return false;
        }
        else if (qty < 0) {
            KevinShop.MessageBox.Alert("必须输入有效的数量。");
            return false;
        } else if (qty > lqty) {
            KevinShop.MessageBox.Alert("该商品每单限购" + lqty + "。");
            return false;
        }
        return true;
    }

};
/* Comm TimePick */
KevinShop.Common.TimePick = function () {
    $(".lxftime").each(function () {
        var lxfday = $(this).attr("lxfday"); //用来判断是否显示天数的变量
        var end = $(this).attr("endtime");
        var endtime = new Date(end.replace(/-/g, "/")).getTime(); //取结束日期(毫秒值)
        var nowtime = new Date().getTime();        //今天的日期(毫秒值)
        var youtime = endtime - nowtime; //还有多久(毫秒值)
        var seconds = youtime / 1000;
        var minutes = Math.floor(seconds / 60);
        var hours = Math.floor(minutes / 60);
        var days = Math.floor(hours / 24);
        var CDay = days;
        var CHour = hours % 24;
        var CMinute = minutes % 60;
        var CSecond = Math.floor(seconds % 60); //"%"是取余运算，可以理解为60进一后取余数，然后只要余数。
        if (endtime <= nowtime) {
            $(this).html("已过期"); //如果结束日期小于当前日期就提示过期啦
        } else {

            if ($(this).attr("lxfday") == "no" || days===0) {
                $(this).html("剩余：<span>" + CHour + "</span>:<span>" + CMinute + "</span>:<span>" + CSecond + "</span>");          //输出没有天数的数据
            } else {
                $(this).html("<span>" + days + "</span>天 <span>" + CHour + "</span>:<span>" + CMinute + "</span>:<span>" + CSecond + "</span> ");          //输出有天数的数据
            }
        }
    });
    setTimeout("KevinShop.Common.TimePick()", 1000);
};

document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
    WeixinJSBridge.call('hideToolbar');
    WeixinJSBridge.call('showOptionMenu');
}, false);